<template>
  <div class="content">
    <div class="topBox" ref="topBox">
        <div class="leftTitle">质检模版</div>
        <div class="rightHandleBox">
          <t-dropdown class="batch" trigger="click" @click="clickHandler">
            <t-space>
              <t-button>
                <svg-icon
                    :name="'icon-batch'"
                    class-name="batch-svg-icon"
                ></svg-icon>
                <span class="name">批量操作</span>
                <svg-icon
                    :name="'icon-batchDown'"
                    class-name="batch-svg-icon"
                ></svg-icon>
              </t-button>
            </t-space>
            <template #dropdown>
              <t-dropdown-menu>
                <t-dropdown-item :value="1" :disabled="hasPermission('template:export')">
                  <template #prefixIcon>
                    <svg-icon :name="'icon-exportIn'"></svg-icon>
                  </template>
                  <span>批量导入</span>
                </t-dropdown-item>
                <t-dropdown-item :value="2" :disabled="tableState.tableData.length === 0 || hasPermission('template:export')">
                  <template #prefixIcon>
                    <svg-icon :name="'icon-export'"></svg-icon>
                  </template>
                  <span>批量导出</span>
                </t-dropdown-item>
                <t-dropdown-item :value="3" :disabled="selectedRowKeys.length === 0 || hasPermission('template:delete')">
                  <template #prefixIcon>
                    <svg-icon :name="'icon-batchDel'"></svg-icon>
                  </template>
                  <span>批量删除</span>
                </t-dropdown-item>
              </t-dropdown-menu>
            </template>
          </t-dropdown>

          <t-button class="addBtn" theme="primary" @click="handleAdd(true, {})" v-permission="['template:save']">
            <template #icon>
              <svg-icon
                  :name="'icon-add'"
                  class-name="add-svg-icon"
              ></svg-icon>
            </template>
            新增模版
          </t-button>
        </div>
    </div>
    <div class="tableBox">
      <div style="position: relative">
        <t-table
            :loading="isLoading"
            :height="tableHeight"
            ref="tableRef"
            row-key="id"
            :data="tableState.tableData"
            :columns="tableState.columns"
            :selected-row-keys="selectedRowKeys"
            @select-change="handleSelectChange"
        >
          <template #handle="{ row }">
            <t-button theme="primary" class="rowConfig" @click="handleConfig(row)" v-permission="['template:info']">
              <template #icon>
                <svg-icon
                    :name="'icon-rowConfig'"
                    class-name="row-svg-icon"
                ></svg-icon>
              </template>
              配置
            </t-button>

            <t-button theme="primary" class="rowEdit" @click="handleAdd(false, row)" v-permission="['template:update']">
              <template #icon>
                <svg-icon
                    :name="'icon-rowEdit'"
                    class-name="row-svg-icon"
                ></svg-icon>
              </template>
              编辑
            </t-button>

            <t-button theme="primary" class="rowDel" @click="handleDel(false ,row)" v-permission="['template:delete']">
              <template #icon>
                <svg-icon
                    :name="'icon-rowDel'"
                    class-name="row-svg-icon"
                ></svg-icon>
              </template>
              删除
            </t-button>
          </template>
        </t-table>
        <div class="emptyBox" v-if="tableState.tableData.length === 0">
          <svg-icon
              :name="'icon-emptyTable'"
              class-name="emptyTable-svg-icon"
          ></svg-icon>
          <span>暂无数据</span>
        </div>
      </div>
    </div>
    <div class="footerBox">
      <t-pagination
          v-model="current"
          v-model:pageSize="pageSize"
          :pageSizeOptions="[10, 20, 30, 50]"
          :total="totalNum"
          size="small"
          show-jumper
          @page-size-change="onPageSizeChange"
          @current-change="onCurrentChange"
      />
    </div>

<!--    新增 ｜ 编辑-->
    <t-dialog
        v-model:visible="addModuleVisible"
        class="ruleDialog"
        width="385"
        :header="moduleTitle"
        v-if="addModuleVisible"
    >
      <t-form
          ref="ruleForm"
          :data="ruleData"
          :label-align="'top'"
          :rules="AHEAD_RULES"
          @reset="ruleReset"
          @submit="ruleSubmit">
        <t-form-item label="模版名称" name="templateName">
          <t-input v-noSpace="ruleData.templateName" v-model="ruleData.templateName" placeholder="请输入模版名称"></t-input>
        </t-form-item>
        <t-form-item label="模板类型" name="type">
          <t-select v-model="ruleData.type" :disabled="!isNewTemplate" placeholder="请选择模版类型">
            <t-option :key="0" label="智能质检"  :value="0" />
            <t-option :key="1" label="标签质检" :value="1" />
          </t-select>
        </t-form-item>
        <t-form-item class="handleRuleBox">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset">取消</t-button>
            <t-button class="hoverBlue" theme="primary" type="submit">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>

<!--    删除 ｜ 批量删除-->
    <t-dialog
        v-model:visible="delVisible"
        theme="info"
        width="431"
        :header="delHeader"
        body=""
        :on-confirm="onClickConfirm"
    />

    <!--    导入组件-->
    <file-upload
        :openUpload="openUpload"
        @closeUpload="closeUpload"
        :downloadTemplate="downloadTemplate"
        :uploadUrl="'/template/import'"
        :queryBody="queryBody"
        :accept="'.json'"
    ></file-upload>
  </div>
</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, watch} from "vue";
import {MessagePlugin} from "tdesign-vue-next";
import { debounce, hasPermission } from "@/utils/tools";
import { useRouter } from "vue-router";
import {
  templateList,
  newTemplate,
  templateDetail,
  editTemplate,
  delTemplate,
  batchDelTemplate,
  isAssociationRecord
} from '@/api/qualitySet/qualityTemplate.js'
import cache from '@/utils/cache.js'
import FileUpload from "@/components/FileUpload/index.vue"
import {templateExport} from "../../../api/qualitySet/qualityTemplate";

const pageInstance = getCurrentInstance()
const router = useRouter()

// 批量操作
const clickHandler = (data) => {
  if(data.value === 1) { // 批量导入
    onClickImport()
  } else if(data.value === 2) { // 批量导出
    let data = {
      pageNo: current.value,
      pageSize: totalNum.value,
      projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
    }
    templateExport(data).then(res => {
      const url = URL.createObjectURL(res) //把blob对象转成一个url
      //创建一个a标签
      const a = document.createElement("a");
      a.href = url; //给a标签上的href属性加上地址
      a.download = "质检模版表.json"; //下载名称
      document.body.appendChild(a); //将a标签添加到文档对象中
      a.click(); //调点击事件
      document.body.removeChild(a); // 一次性的，用完就删除a标签
    }).catch(error => {
      console.log('整体报表导出', error)
    })

  } else {
    handleDel(true, {})
  }
};

// 上传
const uploadUrl = ref()
const queryBody = ref()
const openUpload = ref(false)
const onClickImport = () => {
  // queryBody.value = {projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']}
  uploadUrl.value = import.meta.env.VITE_APP_API + '/template/import'
  // console.log('urlllll', uploadUrl.value)
  // return
  openUpload.value = true
}
const closeUpload = (flag) => {
  openUpload.value = flag
  handleQuery()
}
// 导入模版下载
const downloadTemplate = () => {
  console.log('下载模版')
}

// table
const tableState = reactive({
  tableData: [],
  columns: [
    {
      colKey: 'row-select',
      type: 'multiple',
      width: 90,
    },
    { colKey: '',title: '序号', ellipsis: true, cell:(h, { rowIndex }) => {
        {{
          return rowIndex + (current.value - 1) * pageSize.value + 1 >= 10
              ? rowIndex + (current.value - 1) * pageSize.value + 1
              : "0" + (rowIndex + (current.value - 1) * pageSize.value + 1)
        }}
      }
    },
    { colKey: 'templateName', title: '模版名称', ellipsis: true },
    { colKey: 'type', title: '模板类型', ellipsis: true, cell:(h, { row }) => {
        {{
          return ['智能质检', '标签质检'][row.type]
        }}
      }
    },
    { colKey: 'createBy', title: '创建人', ellipsis: true },
    { colKey: 'updateTime', title: '修改时间', ellipsis: true },
    { colKey: 'handle', title: '操作', align: 'center', width: 260},
  ],
})
const selectedRowKeys = ref([])
const handleSelectChange = (value, ctx) => {
  selectedRowKeys.value = value;
};

// 分页
const current = ref(1);
const pageSize = ref(10);
const totalNum = ref(0)
const onPageSizeChange = (size) => {
  pageSize.value = size
  handleQuery()
};
const onCurrentChange = (index, pageInfo) => {
  current.value = index
  handleQuery()
};

// 查询
const isLoading = ref(false)
const handleQuery = () => {
  isLoading.value = true
  let data = {
    pageNo: current.value,
    pageSize: pageSize.value,
    projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
  }
  templateList(data).then(res => {
    if(res.code === 0) {
      tableState.tableData = res.data.list
      current.value = res.data['currPage']
      pageSize.value = res.data['pageSize']
      totalNum.value = res.data['totalCount']
    }
    isLoading.value = false
  })
}

// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
  nextTick(() => {
    const otherHeight = pageInstance.refs.topBox.offsetHeight
    const windowHeight = window.innerHeight
    tableHeight.value = windowHeight - otherHeight - 162
  })
}

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 0)
onMounted(() => {
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
  handleQuery()
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

// 配置
const handleConfig = (row) => {
  let data = {
    id: row.id,
    templateName: row.templateName,
    type: row.type,
  }
  cache.setSession('templateInfo', JSON.stringify(data))
  console.log(12345,data)
  router.push('/qualitySet/configTemplate')
}

// 新增、编辑检模版
const addModuleVisible = ref(false)
const isNewTemplate = ref(true)
const moduleTitle = ref('')
const rowData = ref({})
const ruleData = reactive({
  projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
  templateName: '',
  type: null,
});
const handleAdd = (flag, row) => {
  rowData.value = row
  isNewTemplate.value = flag
  ruleData.templateName = !flag ? row.templateName : ''
  ruleData.type = !flag ? row.type : null
  moduleTitle.value = !flag ? '编辑检模版' : '新增检模版'
  addModuleVisible.value = true

  // 编辑调用详情接口
  if(!flag) {
    templateDetail(row.id).then(res => {
      if(res.code === 0) {
        ruleData.templateName = res.data.templateName
        ruleData.type = res.data.type
        ruleData.id = res.data.id
        ruleData.inspectionItems = res.data.inspectionItems
      }
    })
  }
}
const AHEAD_RULES = {
  templateName: [ { required: true, message: '请输入模版名称' ,type: 'error', trigger: 'blur'}],
  type: [ { required: true, message: '请选择模版类型' ,type: 'error', trigger: 'change'}],
}
const ruleSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    if(isNewTemplate.value) { // 新增
      ruleData.inspectionItems = []
      if(ruleData['id']) delete ruleData['id']
      newTemplate(ruleData).then(res => {
        if(res.code === 0) {
          pageInstance.refs.ruleForm.reset()
          addModuleVisible.value = false
          handleQuery()
          MessagePlugin.success('新增成功！');
        }
      })
    } else { // 编辑
      editTemplate(ruleData).then(res => {
        if(res.code === 0) {
          pageInstance.refs.ruleForm.reset()
          addModuleVisible.value = false
          handleQuery()
          MessagePlugin.success('编辑成功！');
        }
      })
    }
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
    // MessagePlugin.warning(firstError);
  }
};
const ruleReset = () => {
  addModuleVisible.value = false
}
// 删除
const delVisible = ref(false)
const delHeader = ref('')
const isBatchDel = ref(false) // 是否是批量删除
const delRowId = ref(null)
const handleDel = (flag, row) => {
  isAssociationRecord(row.id).then((res) => {
    if(res.data) {
      delHeader.value = flag? '是否确认删除？' :  '该模板已被录音使用，请确认是否删除?'
    } else {
      delHeader.value = flag? '是否确认删除？' : '您确认删除此模版吗？'
    }
    isBatchDel.value = flag
    delRowId.value = row.id
    delVisible.value = true
  })
}
const onClickConfirm = (context) => {
  if(isBatchDel.value) { // 批量删除
    batchDelTemplate(selectedRowKeys.value).then(res => {
      if(res.code === 0) {
        MessagePlugin.success('批量删除成功！')
        delVisible.value = false
        if(tableState.tableData.length - selectedRowKeys.value.length === 0) {
          current.value = current.value > 1 ? current.value - 1 : current.value
        }
        handleQuery()
      }
    })
  } else { // 列表删除
    delTemplate(delRowId.value).then(res => {
      if(res.code === 0) {
        MessagePlugin.success('删除成功！')
        delVisible.value = false
        if(tableState.tableData.length - 1 === 0) {
          current.value = current.value > 1 ? current.value - 1 : current.value
        }
        handleQuery()
      }
    }).catch(error => {
      delVisible.value = false
    })
  }
};
const onClickCancel = () => {
  delVisible.value = false
}
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  overflow: hidden;
  padding: 8px 8px 0 8px;
  background-color: #EBECED!important;
}
.topBox {
  background-color: rgba(255, 255,255, 1);
  padding: 0 16px;
  height: 67px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px 4px 0 0;
  .leftTitle {
    font-size: 16px;
    font-weight: 600;
    color: rgba(51, 51, 51, 1);
    text-align: left;
  }
  .rightHandleBox {
    margin-left: auto;
    .addBtn {
      //float: right;
      width: 101px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(30, 117, 254, 1);
      padding: 5px 0;
      font-size: 12px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      .add-svg-icon {
        height: 16px;
        width: 16px;
        margin-right: 7px;
      }
    }
    .addBtn:hover {
      background: var(--Brand-Brand6-Hover, #458DFF) !important;
      color: var(--text-icon-font-wh-190-anti, rgba(255, 255, 255, 0.90)) !important;
    }
    .batch {
      margin-right: 10px;
      .t-button {
        width: 102px;
        height: 28px;
        background: rgba(227, 238, 255, 1);
        border-radius: 3px;
        border: 0.5px solid rgba(9.38399999999999, 95.71679999999998, 234.6, 1);
        padding: 6px 8px;
        vertical-align: middle;
        .batch-svg-icon {
          display: inline-block;
          height: 16px;
          width: 16px;
          color: rgba(30, 117, 254, 1);
          position:relative;
          top:3px;
        }
        .t-button__text {
          span {
            display: inline-block;
            margin: 0 4px;
            font-size: 12px;
            font-weight: 400;
            color: rgba(30, 117, 254, 1);
          }
        }
      }
      .t-button:hover {
        background: var(--Brand-Brand1-Light, #EDF2FD) !important;
        color: var(--Brand-Brand6-Hover, #458DFF) !important;
        border: 1px solid var(--Brand-Brand6-Hover, #458DFF) !important;
      }
    }
  }
}
.tableBox {
  :deep(.t-table__header) {
    tr {
      th {
        padding: 7px 10px;
        box-sizing: border-box;
      }
      th:nth-child(1) {
        padding: 7px 5px 7px 65px;
      }
      th:nth-child(2) {
        padding-left: 0;
      }
    }
  }
  :deep(.t-table__body) {
    tr {
      td {
        padding: 6px 10px;
        box-sizing: border-box;
      }
      td:nth-child(1) {
        padding: 7px 5px 7px 65px;
      }
      td:nth-child(2) {
        padding-left: 0;
      }
    }
    .t-button {
      border: none;
      width: 56px;
      height: 26px;
      opacity: 1;
      border-radius: 3px;
      font-size: 13px;
      font-weight: 400;
      padding: 0;
      margin: 0 4px;
      .row-svg-icon {
        height: 12px;
        width: 12px;
        margin-right: 2px;
      }
    }
    .rowDel {
      background: rgba(255, 224, 224, 1);
      color: rgba(227, 77, 89, 1);
    }
    .rowConfig {
      background: rgba(255, 238, 224, 1);
      color: rgba(255, 153, 0, 1);
    }
    .rowEdit {
      background: rgba(227, 238, 255, 1);
      color: rgba(30, 117, 254, 1);
    }
  }
}
:deep(.t-table__empty) {
  display: none;
}
.emptyBox {
  position: absolute;
  height: 116px;
  width: 69px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  .emptyTable-svg-icon {
    height: 62px;
    width: 69px;
  }
  span {
    font-size: 12px;
    font-weight: 400;
    color: rgba(92, 91, 91, 1);
  }
}
:deep(.t-dialog) {
  padding: 22px 22px 18px 22px;
  .t-icon.t-is-info {
    color: rgba(30, 117, 254, 1) ;
  }
  .t-dialog__body__icon {
    display: none;
  }
  .t-dialog__footer {
    padding-top: 31px;
    .t-dialog__cancel {
      background-color: white;
      border: none;
      width: 60px;
      height: 28px;
    }
    .t-dialog__confirm {
      width: 60px;
      height: 28px;
      opacity: 1;
      border-radius: 3px;
      background: rgba(30, 117, 254, 1);
    }
    .t-dialog__confirm:hover {
      background: var(--Brand-Brand6-Hover, #458DFF) !important;
      color: var(--text-icon-font-wh-190-anti, rgba(255, 255, 255, 0.90)) !important;
    }
  }
}
:deep(.ruleDialog .t-dialog__wrap .t-dialog__position .t-dialog) {
  .t-dialog__footer {
    display: none !important;
  }
  .t-dialog__body {
    .t-form__item {
      margin-bottom: 16px;
    }
    padding-bottom: 0;
    .t-input {
      height: 28px;
    }
  }
}
.handleRuleBox {
  padding-top: 15px;
  margin-bottom: 0 !important;
  :deep(.t-form__label) {
    font-size: 14px;
    font-weight: 400;
    color: rgba(227, 60, 100, 0.9);

  }
  :deep(.t-form__controls) {
    text-align: right;
  }
  :deep(.t-form__controls-content) {
    display: inline-block;
    position: absolute;
    right: 0;
  }
  .t-button--theme-default {
    background-color: white;
    border: none;
    width: 60px;
    height: 28px;
  }
  .t-button--theme-primary {
    width: 60px;
    height: 28px;
    opacity: 1;
    border-radius: 3px;
    background: rgba(30, 117, 254, 1);
  }
}
.footerBox {
  background-color: rgba(255,255,255,1);
  width: calc(100% - 16px);
  position: absolute;
  bottom: 8px;
  overflow: hidden;
  border-radius: 0 0 4px 4px;
}
</style>

